package com.jytc.framework.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.jytc.framework.bo.FwPermissionBO;
import com.jytc.framework.bo.FwRoleBO;
import com.jytc.framework.commons.AdminLoginToken;
import com.jytc.framework.commons.Page;
import com.jytc.framework.commons.PermissionTree;
import com.jytc.framework.commons.PropertyFilter;
import com.jytc.framework.commons.ResultInfos;
import com.jytc.framework.constants.CommonConstants;
import com.jytc.framework.constants.RequestNameConstants;
import com.jytc.framework.constants.ResultConstants;
import com.jytc.framework.constants.SessionNameConstants;
import com.jytc.framework.constants.UrlConstants;
import com.jytc.framework.dto.FwPermissionDTO;
import com.jytc.framework.dto.FwRoleDTO;
import com.jytc.framework.po.FwRole;
import com.jytc.framework.po.FwRolePermission;
import com.jytc.framework.utils.HibernateWebUtils;
import com.jytc.framework.utils.SessionUtils;

/**
 * @title: FSysRoleController.java
 * @description: 角色管理
 * 
 * @author: dongyuese
 *
 */
@Controller
@RequestMapping("/admin/jsp/roleMgr.do")
public class FwRoleController
{
	protected Logger logger = LoggerFactory.getLogger(getClass());//日志

	/**
	 * 查询展示页面
	 */
	private final String QUERY_GOTO_URL = "/admin/jsp/org_mgr/role_mgr/role_mgr.jsp";

	/**
	 * 编辑页面
	 */
	private final String EDIT_GOTO_URL = "/admin/jsp/org_mgr/role_mgr/role_edit.jsp";

	/**
	 * 增加页面
	 */
	private final String ADD_GOTO_URL = "/admin/jsp/org_mgr/role_mgr/role_add.jsp";

	/**
	 * 查询URL
	 */
	private final String VIEW_URL = "/admin/jsp/roleMgr.do?method=queryRole";

	/**
	 * 新增URL
	 */
	private final String ADD_URL = "/admin/jsp/roleMgr.do?method=addRole";

	/**
	 * 编辑URL
	 */
	private final String EDIT_URL = "/admin/jsp/roleMgr.do?method=editRole";

	/**
	 * 角色管理业务操作类
	 */
	@Autowired
	private FwRoleBO fwRoleBO;

	/**
	 * 权限信息业务操作类
	 */
	@Autowired
	private FwPermissionBO fwPermissionBO;

	@RequestMapping(params = "method=queryRole")
	public ModelAndView queryRole(HttpServletRequest request, ModelMap model, Page page)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			List<PropertyFilter> filters = HibernateWebUtils.buildPropertyFilters(request);
			Page pageResult = fwRoleBO.query(page, filters);

			model.addAttribute(RequestNameConstants.PAGE_OBJECT, pageResult);
		} catch (Exception e)
		{
			logger.error("角色查询异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.QUERY_ERROR));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(false);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(QUERY_GOTO_URL);
	}

	/**
	 * 角色新增页面转向方法
	 * @param request 请求对象
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "method=addRole")
	public ModelAndView addRole(HttpServletRequest request, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			this.initPermissionTree(request, null);
		} catch (Exception e)
		{
			logger.error("角色新增初始化异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.QUERY_ERROR));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(VIEW_URL);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(ADD_GOTO_URL);
	}

	/**
	 * 保存角色信息
	 * @param request 请求对象
	 * @param sysRoleDTO　角色信息数据传输对象
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "method=saveRole")
	public ModelAndView saveRole(HttpServletRequest request, FwRoleDTO fwRoleDTO, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			AdminLoginToken loginToken = (AdminLoginToken) SessionUtils.getObjectAttribute(request,
					SessionNameConstants.ADMIN_LOGIN_TOKEN);
			fwRoleDTO.setDeptId(loginToken.getFwUser().getDeptId());

			int addFlag = fwRoleBO.save(fwRoleDTO);

			//判断保存是否成功
			if (addFlag == ResultConstants.INSERT_SUCCEED)
			{
				resultInfos.setPromptInfo(ResultConstants.getResultInfo(addFlag));
				resultInfos.setIsBack(false);
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(ADD_URL);
			} else
			{
				resultInfos.setPromptInfo("角色名称重复");
				resultInfos.setIsBack(true);
			}
			this.initPermissionTree(request, null);
		} catch (Exception e)
		{
			logger.error("单位新增异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.INSERT_ERROR));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(ADD_URL);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(UrlConstants.INFORMATION_PAGE);
	}

	/**
	 * 按照角色ID删除角色信息
	 * @param roleId　角色ID
	 * @param modeld
	 * @return
	 */
	@RequestMapping(params = "method=delRole")
	public ModelAndView delRole(Integer roleId, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			int delFlag = fwRoleBO.deleteById(roleId);

			//判断删除是否成功
			if (delFlag == ResultConstants.DELETE_SUCCEED)
			{
				resultInfos.setPromptInfo(ResultConstants.getResultInfo(delFlag));
				resultInfos.setIsBack(false);
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(VIEW_URL);
			} else if (delFlag == CommonConstants.ROLE_USER_QUOTED)
			{
				resultInfos.setPromptInfo("角色已被用户引用，不能删除");
				resultInfos.setIsBack(true);
			}
		} catch (Exception e)
		{
			logger.error("角色删除异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.DELETE_ERR0R));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(VIEW_URL);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(UrlConstants.INFORMATION_PAGE);
	}

	/**
	 * 批量删除角色信息
	 * @param roleId　角色ID集合
	 * @param modeld
	 * @return
	 */
	@RequestMapping(params = "method=delRoles")
	public ModelAndView delRoles(Integer[] roleId, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			int delFlag = fwRoleBO.deleteByIds(roleId);

			//判断删除是否成功
			if (delFlag == ResultConstants.DELETE_SUCCEED)
			{
				resultInfos.setPromptInfo(ResultConstants.getResultInfo(delFlag));
				resultInfos.setIsBack(false);
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(VIEW_URL);
			} else
			{
				resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.DELETE_FAILED));
				resultInfos.setIsBack(true);
			}
		} catch (Exception e)
		{
			logger.error("角色批量删除异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.DELETE_ERR0R));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(VIEW_URL);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(UrlConstants.INFORMATION_PAGE);
	}

	/**
	 * 角色修改初始化页面
	 * @param roleId　角色ID
	 * @param modeld
	 * @return
	 */
	@RequestMapping(params = "method=editRole")
	public ModelAndView editRole(HttpServletRequest request, Integer roleId, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			FwRole fwRole = fwRoleBO.findById(roleId);
			model.addAttribute(RequestNameConstants.RESULT_OBJECT, fwRole);

			List<String> defaultCheckedNodes = new ArrayList<String>();
			for (FwRolePermission rolePermission : fwRole.getFwRolePermissions())
			{
				defaultCheckedNodes.add(String.valueOf(rolePermission.getFwPermission().getPermissionId()));
			}
			this.initPermissionTree(request, defaultCheckedNodes);
		} catch (Exception e)
		{
			logger.error("角色编辑异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.EDIT_ERROR));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(VIEW_URL);
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(EDIT_GOTO_URL);
	}

	/**
	 * 修改角色信息
	 * @param sysRoleDTO　角色信息数据传输对象
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "method=updRole")
	public ModelAndView updRole(FwRoleDTO fwRoleDTO, ModelMap model)
	{
		ResultInfos resultInfos = new ResultInfos();
		model.addAttribute(RequestNameConstants.RESULT_INFO, resultInfos);
		try
		{
			int updFlag = fwRoleBO.update(fwRoleDTO);

			//判断修改是否成功
			if (updFlag == ResultConstants.UPDATE_SUCCEED)
			{
				resultInfos.setPromptInfo(ResultConstants.getResultInfo(updFlag));
				resultInfos.setIsBack(false);
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(VIEW_URL);
			} else if (updFlag == CommonConstants.ROLE_IS_EXIST)
			{
				resultInfos.setPromptInfo("角色名称重复");
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(EDIT_URL + "&&roleId=" + fwRoleDTO.getRoleId());
				return new ModelAndView(UrlConstants.INFORMATION_PAGE);
			} else if (updFlag == CommonConstants.ROLE_USER_QUOTED)
			{
				resultInfos.setPromptInfo("角色已被用户引用，不能设置为无效");
				resultInfos.setIsRedirect(true);
				resultInfos.setGotoUrlForward(EDIT_URL + "&&roleId=" + fwRoleDTO.getRoleId());
				return new ModelAndView(UrlConstants.INFORMATION_PAGE);
			}
		} catch (Exception e)
		{
			logger.error("角色修改异常", e);

			// 显示提示信息
			resultInfos.setPromptInfo(ResultConstants.getResultInfo(ResultConstants.UPDATE_ERROR));
			resultInfos.setIsBack(false);
			resultInfos.setIsRedirect(true);
			resultInfos.setGotoUrlForward(EDIT_URL + "&&roleId=" + fwRoleDTO.getRoleId());
			return new ModelAndView(UrlConstants.INFORMATION_PAGE);
		}
		return new ModelAndView(UrlConstants.INFORMATION_PAGE);
	}

	/**
	 * 初始化权限树数据
	 * @param request
	 * @throws Exception
	 */
	private void initPermissionTree(HttpServletRequest request, List<String> defaultCheckedNodes) throws Exception
	{
		List<FwPermissionDTO> permissions = fwPermissionBO.findAll();
		PermissionTree permissionTree = new PermissionTree();
		permissionTree.setPermissions(permissions);
		permissionTree.setDefaultCheckedNodes(defaultCheckedNodes);
		request.setAttribute("permissionTree", permissionTree);
	}

}
